import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { indexOf } from 'lodash';
import {
  Row,
  Col,
  Card,
  Form,
  Select,
  Button,
  message,
  Popconfirm,
  Tabs,
  Table,
  Dropdown,
  Menu,
  notification,
  Alert,
  Icon,
} from 'antd';

const TabPane = Tabs.TabPane;
import { convertProjectCode } from './components/toolkit';
import PlaceForm from './components/PlaceForm';
import { tableChangePagination } from './components/Pagination';

import styles from './TableList.less';
import { isNull } from 'util';

const FormItem = Form.Item;
const { Option } = Select;

@connect(({ zubie, gameList, place, loading }) => ({
  zubie,
  gameList,
  place,
  loading: loading.models.zubie,
}))
@Form.create()
export default class MatchView extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    zubieBGColor: {},
    zubieTextColor: {},
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    const pathArray = location.pathname.split('/');
    const id = pathArray[3];
    this.setState({
      id,
    });

    dispatch({
      type: 'zubie/clean',
      payload: {},
    });

    dispatch({
      type: 'gameList/findById',
      payload: id,
      callback: () => {
        // this.props.dispatch({
        //   type: 'zubie/queryZhixu',
        //   payload: {
        //     gameId: id,
        //   },
        // });
        dispatch({
          type: 'zubie/queryAllZubieForGame',
          callback: () => {
            let zubieBGColor = {};
            let zubieTextColor = {};
            const colors = [
              '#290C44',
              '#ECF10E',
              '#ED06A7',
              '#0AF506',
              '#06BEBC',
              '#1890FF',
              'red',
              'yellow',
              'black',
              'orange',
              'pink',
            ];
            const textColors = [
              'white',
              'green',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
              'white',
            ];
            this.props.zubie.zubieList.forEach((element, index) => {
              if (element.enabled) {
                zubieBGColor[element.code] = colors[index];
                zubieTextColor[element.code] = textColors[index];
              }
            });
            this.setState({ zubieBGColor: zubieBGColor });
            this.setState({ zubieTextColor: zubieTextColor });
            this.props.dispatch({
              type: 'place/findPlaceData',
              payload: { gameId: id },
            });

            this.props.dispatch({
              type: 'zubie/queryNotSetPlaceGame',
              payload: {
                gameId: id,
              },
            });

            // this.props.dispatch({
            //   type: 'zubie/queryFanganHeader',
            //   payload: {
            //     gameId: id,
            //   },
            //   callback: ()=> {
            //     this.props.dispatch({
            //       type: 'zubie/queryFangan',
            //       payload: {
            //         gameId: id,
            //       }
            //     })
            //   },
            // })
            this.props.dispatch({
              type: 'place/findPlaceForGame',
            });
          },
        });
      },
    });
  }

  showItemMenu = item => {
    return (
      <Menu>
        <Menu.Item>
          <Popconfirm
            title="是否确定取消分配。 "
            onConfirm={() => this.cancelSetPlace(item)}
            okText="Yes"
            cancelText="No"
          >
            <Button>取消分配</Button>
          </Popconfirm>
        </Menu.Item>
      </Menu>
    );
  };

  cancelSetPlace = item => {
    this.props.dispatch({
      type: 'zubie/cancelSetPlace',
      payload: {
        code: item.code,
        zubieCode: item.zubieCode,
      },
      callback: () => {
        message.success('取消成功');
        this.props.dispatch({
          type: 'place/findPlaceData',
          payload: { gameId: this.state.id },
        });

        this.props.dispatch({
          type: 'zubie/queryNotSetPlaceGame',
          payload: {
            gameId: this.state.id,
          },
        });
      },
    });
  };

  renderSimpleForm() {
    const {
      zubie: { curZubieObj, zubieList, curZubie, phaseList },
    } = this.props;
    return (
      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
        <Col md={8} sm={24}>
          <FormItem label="请选择组别">
            <Select
              placeholder="未选择"
              style={{ width: '100%' }}
              onChange={this.onSelectZubie}
              value={curZubie}
            >
              {zubieList.map(element => {
                if (element.enabled)
                  return (
                    <Option key={'OP' + element.code} value={element.code}>
                      {convertProjectCode(element.projectCode) + ' - ' + element.zubieName}
                    </Option>
                  );
              })}
            </Select>
          </FormItem>
        </Col>
        {!curZubie && (
          <Col md={4} sm={16}>
            <FormItem>
              <Alert
                style={{ flex: 1 }}
                message="请选择一个组别"
                type="error"
                icon={<Icon type="left" />}
                showIcon={true}
              />
            </FormItem>
          </Col>
        )}
      </Row>
    );
  }

  generateJiemuMap = () => {
    var jiemuMap = {};
    this.props.zubie.zhixuList.list &&
      this.props.zubie.zhixuList.list.map(element => {
        jiemuMap[element.bisaiId] = element;
      });
    return jiemuMap;
  };

  renderBianpai = item => (
    <Dropdown overlay={this.showItemMenu(item)} trigger={['contextMenu']} placement="bottomCenter">
      <div
        style={{
          textAlign: 'center',
          backgroundColor: this.state.zubieBGColor[item.zubieCode],
          color: this.state.zubieTextColor[item.zubieCode],
        }}
      >
        <div
          style={{
            borderStyle: 'none none solid none',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
          }}
        >
          {item.bisaiId}
        </div>
        <div>
          {' '}
          {item.zubieName}({item.projectCode})
        </div>
        <div>
          {' '}
          {item.phaseName} 第{item.round}轮
        </div>
        <div
          style={{
            display: 'flex',
            borderStyle: 'solid none none none',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
          }}
        >
          <span
            style={{
              flex: 1,
              borderStyle: 'none solid none none',
              borderWidth: '1px',
              borderColor: '#e8e8e8',
            }}
          >
            {item.gamePosName1}
          </span>
          <span style={{ flex: 1 }}>{item.gamePosName2}</span>
        </div>

        {this.renderJiemuAthlete(item)}
        <div style={{ display: 'flex' }}>
          <span
            style={{
              flex: 1,
              borderStyle: 'none solid none none',
              borderWidth: '1px',
              borderColor: '#e8e8e8',
            }}
          >
            {item.team1}
          </span>
          <span style={{ flex: 1 }}>{item.team2}</span>
        </div>
      </div>
    </Dropdown>
  );

  renderJiemu = item => (
    <div
      style={{
        textAlign: 'center',
        backgroundColor: item.zubieCode === this.props.zubie.curZubie ? '#1890FF' : '',
        color: item.zubieCode === this.props.zubie.curZubie ? '#ffffff' : '',
      }}
    >
      <div
        style={{ borderStyle: 'none none solid none', borderWidth: '1px', borderColor: '#e8e8e8' }}
      >
        {item.bisaiId}
      </div>
      <div>
        {' '}
        {item.zubieName}({item.projectCode})
      </div>
      <div>
        {' '}
        {item.phaseName} 第{item.round}轮
      </div>
      <div
        style={{
          display: 'flex',
          borderStyle: 'solid none none none',
          borderWidth: '1px',
          borderColor: '#e8e8e8',
        }}
      >
        <span
          style={{
            flex: 1,
            borderStyle: 'none solid none none',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
          }}
        >
          {item.gamePosName1}
        </span>
        <span style={{ flex: 1 }}>{item.gamePosName2}</span>
      </div>
      {this.renderJiemuAthlete(item)}
      <div style={{ display: 'flex' }}>
        <span
          style={{
            flex: 1,
            borderStyle: 'none solid none none',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
          }}
        >
          {item.team1}
        </span>
        <span style={{ flex: 1 }}>{item.team2}</span>
      </div>
    </div>
  );

  renderJiemuAthlete = item => {
    const userList1 = item.athlethList1.map((value, index, array) => {
      return value.userName;
    });

    const userList2 = item.athlethList2.map((value, index, array) => {
      return value.userName;
    });
    return (
      <div>
        <div
          style={{
            display: 'flex',
            borderStyle: 'solid none solid none',
            borderWidth: '1px',
            borderColor: '#e8e8e8',
          }}
        >
          <div
            style={{
              flex: 1,
              borderStyle: 'none solid none none',
              borderWidth: '1px',
              borderColor: '#e8e8e8',
            }}
          >
            {userList1.join(',')}
          </div>
          <div style={{ flex: 1 }}>{userList2.join(',')}</div>
        </div>
      </div>
    );
  };

  handleZhixuTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const params = tableChangePagination(pagination, filtersArg, sorter);
    (params.zubieCode = this.props.zubie.curZubie),
      this.props.dispatch({
        type: 'zubie/queryZhixu',
        payload: params,
      });
  };

  downloadFangan = () => {
    if (this.props.zubie.curZubie)
      window.open('/bgms/gameScore/download/' + this.props.zubie.curZubie, 'GET');
    else message.warn('请先选择组别');
  };

  startDrag = (e, item) => {
    e.dataTransfer.setData('item', JSON.stringify(item)); // 拖拽元素携带的数据
  };

  dropDrag = (e, zubiePlaceCode, placeCode) => {
    e.preventDefault();
    const itemData = JSON.parse(e.dataTransfer.getData('item'));

    this.props.dispatch({
      type: 'zubie/setKongchang',
      payload: {
        id: itemData.id,
        placeCode: placeCode,
        zubiePlaceCode: zubiePlaceCode,
      },
      callback: () => {
        message.success('设置成功');
        this.props.dispatch({
          type: 'place/findPlaceData',
          payload: { gameId: this.state.id },
        });

        this.props.dispatch({
          type: 'zubie/queryNotSetPlaceGame',
          payload: {
            gameId: this.state.id,
          },
        });
      },
    });
  };

  dragDragOver = e => {
    e.preventDefault(); // 此处的代码是必须的  不然无法拖拽
    //console.log('拖拽中')
  };

  render() {
    const {
      zubie: { curZubieObj, zhixuList, fanganHeader, fanganList, notSetPlaceGameList },
      loading,
      place: { placeList, zubiePlaceList, placeData },
    } = this.props;

    const columns2 = [
      {
        title: '比赛阶段',
        width: 100,
        dataIndex: 'phaseName',
      },
      {
        title: '组别',
        width: 100,
        children: [
          {
            title: '分组',
            width: 100,
            children: [
              {
                title: '人数',
                width: 100,
                align: 'center',
                dataIndex: 'roundName',
              },
            ],
          },
        ],
      },
    ];

    if (fanganHeader.zubieHeader) {
      columns2.push(fanganHeader.zubieHeader);
    } else {
      columns2.push({
        title: '组别名称(待确定)',
        children: [
          {
            title: '待确定',
            children: [
              {
                title: '0',
                align: 'center',
                dataIndex: 'teamCount',
              },
            ],
          },
        ],
      });
    }

    const placeCount = fanganHeader && fanganHeader.placeCount ? fanganHeader.placeCount : 0;

    columns2.push({
      title: '比赛场数',
      width: 100,
      align: 'center',
      dataIndex: 'changShu',
    });
    columns2.push({
      width: 100,
      title: '场地数',
      align: 'center',
      children: [
        {
          title: placeCount,
          width: 100,
          align: 'center',
          dataIndex: 'changdiShu',
        },
      ],
    });

    const columns3 = [
      {
        title: '阶段名称',
        width: 100,
        dataIndex: 'phaseName',
      },
      {
        title: '比赛编号',
        dataIndex: 'bisaiId',
      },
      {
        title: '项目',
        dataIndex: 'project',
      },
      {
        title: '组别',
        dataIndex: 'fenzuName',
      },
      {
        title: '轮次',
        dataIndex: 'roundName',
      },
      {
        title: '抽签号',
        dataIndex: 'gamePosName1',
      },
      {
        title: '所属团队',
        dataIndex: 'team1',
      },
      {
        title: '运动员',
        dataIndex: 'athlethList1',
        render: value => (
          <span>
            {value &&
              value
                .map(value => {
                  return value.userName;
                })
                .join(',')}
          </span>
        ),
      },
      {
        title: '对阵',
        render: () => <span>VS</span>,
      },
      {
        title: '抽签号',
        dataIndex: 'gamePosName2',
      },
      {
        title: '所属团队',
        dataIndex: 'team2',
      },
      {
        title: '运动员',
        dataIndex: 'athlethList2',
        render: value => (
          <span>
            {value &&
              value
                .map(value => {
                  return value.userName;
                })
                .join(',')}
          </span>
        ),
      },
      {
        title: '场地',
        dataIndex: 'placeName',
      },
      {
        title: '场序',
        dataIndex: 'changxu',
      },
      {
        title: '日期',
        dataIndex: 'matchDate',
        render: value => <span>{value && value.substring(0, 10)}</span>,
      },
      {
        title: '时段',
        dataIndex: 'timePhase',
        render: value => {
          switch (value) {
            case 'A':
              return <span>上午</span>;
            case 'B':
              return <span>下午</span>;
            case 'C':
              return <span>晚上</span>;
          }
        },
      },
      {
        title: '时间',
        dataIndex: 'placeTime',
      },
    ];

    const jiemuChangdi = [];

    placeList.map(value => {
      jiemuChangdi.push({
        title: value.name,
        dataIndex: value.code,
        align: 'center',
        render: (item, row) => {
          if (item) {
            return this.renderJiemu(item);
          }
        },
      });
    });

    const bianpaiChangdi = [];

    placeList.map(value => {
      bianpaiChangdi.push({
        title: value.name,
        dataIndex: value.code,
        align: 'center',
        render: (item, row) => {
          if (item) {
            return this.renderBianpai(item);
          } else {
            return (
              <div
                style={{ width: 100, height: 50 }}
                onDrop={e => this.dropDrag(e, row.code, value.code)}
                onDragOver={e => this.dragDragOver(e)}
              />
            );
          }
        },
      });
    });

    const columnBianPai = [
      {
        title: '日期',
        dataIndex: 'matchDate',
        width: 90,
        render: value => <span>{value.substring(0, 10)}</span>,
      },
      {
        title: '时间段',
        dataIndex: 'timePhase',
        width: 60,
        render: value => {
          switch (value) {
            case 'morning':
              return '上午';
            case 'afternoon':
              return '下午';
            case 'night':
              return '晚上';
          }
        },
      },
      {
        title: '场序',
        dataIndex: 'seq',
        width: 50,
      },
      {
        title: '场  地  名  称',
        children: bianpaiChangdi,
      },
    ];

    const columnJiemu = [
      {
        title: '日期',
        dataIndex: 'matchDate',
        width: 90,
        render: value => <span>{value.substring(5, 10)}</span>,
      },
      {
        title: '时间段',
        dataIndex: 'timePhase',
        width: 60,
        render: value => {
          switch (value) {
            case 'morning':
              return '上午';
            case 'afternoon':
              return '下午';
            case 'night':
              return '晚上';
          }
        },
      },
      {
        title: '场序',
        dataIndex: 'seq',
        width: 50,
      },
      {
        title: '场  地  名  称',
        children: jiemuChangdi,
      },
    ];

    const comparePhase = (obj2, obj1) => {
      var val1 = obj1.phaseSeq;
      var val2 = obj2.phaseSeq;
      var val3 = obj1.round;
      var val4 = obj2.round;
      var val5 = obj1.fenzuName;
      var val6 = obj2.fenzuName;
      var val7 = obj1.id;
      var val8 = obj2.id;
      if (val1 < val2) {
        return 1;
      } else if (val1 > val2) {
        return -1;
      } else {
        if (val3 < val4) {
          return 1;
        } else if (val3 > val4) {
          return -1;
        } else {
          if (val5 < val6) {
            return 1;
          } else if (val5 > val6) {
            return -1;
          } else {
            if (val7 < val8) {
              return 1;
            } else if (val7 > val8) {
              return -1;
            } else {
              return 0;
            }
          }
        }
      }
    };

    const columnsMatch2 = [
      {
        title: '比赛编号',
        dataIndex: 'bisaiId',
      },
      {
        title: '轮次',
        dataIndex: 'roundName',
      },
      {
        title: '抽签号',
        dataIndex: 'gamePosName1',
      },
      {
        title: '所属团队',
        dataIndex: 'team1',
      },
      {
        title: '运动员',
        dataIndex: 'athlethList1',
        render: value => (
          <span>
            {value &&
              value
                .map(value => {
                  return value.userName;
                })
                .join(',')}
          </span>
        ),
      },
      {
        title: '对阵',
        render: () => <span>VS</span>,
      },
      {
        title: '抽签号',
        dataIndex: 'gamePosName2',
      },
      {
        title: '所属团队',
        dataIndex: 'team2',
      },
      {
        title: '运动员',
        dataIndex: 'athlethList2',
        render: value => (
          <span>
            {value &&
              value
                .map(value => {
                  return value.userName;
                })
                .join(',')}
          </span>
        ),
      },
      {
        title: '选择',
        width: 100,
        render: (value, item) => (
          <div>
            <Button
              style={{ marginRight: 5 }}
              onClick={() => {
                this.okHandle(item);
                this.close();
              }}
            >
              选择
            </Button>
          </div>
        ),
      },
    ];

    const datas = [];
    let datarow = {};
    let curDataRow = {};
    let t_index = 1;
    const columnNotSet = [];

    notSetPlaceGameList &&
      notSetPlaceGameList.forEach(value => {
        //console.log(value.round,value.phaseCode, value.phaseName , value.roundName )
        if (value.round !== curDataRow.round || value.phaseCode !== curDataRow.phaseCode) {
          if (datarow.round) {
            datas.push(datarow);
          }

          datarow = {};
          datarow.round =
            value.roundName === '决3、4' || value.roundName === '决1、2' ? '决赛' : value.roundName;
          t_index = 1;
        }
        //if (!value.placeCode && !value.zubiePlaceCode) {
        datarow[t_index] = value;
        curDataRow = value;
        if (columnNotSet.indexOf(t_index) === -1) {
          columnNotSet.push(t_index);
        }
        t_index++;
        //}
      });

    datas.push(datarow);

    //datas.sort(comparePhase);
    //console.log(notSetPlaceGameList);

    const columnsMatch = [
      {
        title: '',
        dataIndex: 'round',
        width: 70,
      },
    ];

    columnNotSet.forEach(value =>
      columnsMatch.push({
        title: value,
        dataIndex: value,
        render: (item, record) =>
          item && (
            <div
              style={{
                backgroundColor: this.state.zubieBGColor[item.zubieCode],
                color: this.state.zubieTextColor[item.zubieCode],
              }}
              draggable={true}
              onDragStart={e => this.startDrag(e, item)}
            >
              <div>
                {item.zubieName}({item.projectCode})
              </div>
              <div>
                {item.fenzuName}组 {item.fenzuSeq} / {item.gamePosName1}-{item.gamePosName2}
              </div>
            </div>
          ),
      })
    );

    return (
      <Fragment>
        <Card>
          <div className={styles.tableList}>
            <Tabs
              tabBarExtraContent={
                <div>
                  <Button>下载节目单</Button>
                </div>
              }
            >
              <TabPane tab="编排" key="bianpaiT" style={{ display: 'flex' }}>
                <Table
                  size="small"
                  loading={loading}
                  pagination={false}
                  bordered
                  dataSource={placeData}
                  columns={columnBianPai}
                  style={{ flex: 1, marginRight: 10 }}
                  scroll={{ y: 500 }}
                />

                <Table
                  dataSource={datas}
                  pagination={false}
                  size="small"
                  columns={columnsMatch}
                  style={{ flex: 1 }}
                  bordered
                  scroll={{ y: 500 }}
                />
              </TabPane>
              <TabPane tab="节目单" key="zhixuT">
                <Table
                  size="small"
                  loading={loading}
                  pagination={false}
                  bordered
                  dataSource={placeData}
                  columns={columnJiemu}
                  style={{ flex: 1, marginRight: 10 }}
                />
              </TabPane>
              <TabPane tab="比赛方案" key="fanganT">
                <Table
                  size="small"
                  loading={loading}
                  dataSource={fanganList}
                  pagination={false}
                  columns={columns2}
                  bordered
                  //onSelectRow={this.handleSelectRows}
                  onChange={this.handleZhixuTableChange}
                />
              </TabPane>
            </Tabs>
          </div>
        </Card>
      </Fragment>
    );
  }
}
